#include <am.h>
#include <klib-macros.h>

extern char _heap_start;
extern int main(const char *args);

extern char _pmem_start;
#define PMEM_SIZE (128 * 1024 * 1024)
#define PMEM_END  ((uintptr_t)&_pmem_start + PMEM_SIZE)

Area heap = RANGE(&_heap_start, PMEM_END);
#ifndef MAINARGS
#define MAINARGS ""
#endif
static const char mainargs[] = MAINARGS;

void putch(char ch) {
  asm volatile("mv a0, %0; .word 0x0000007b" : :"r"(ch));
}

void halt(int code) {
  asm volatile("mv a0, %0; .word 0x0000006b" : :"r"(code));
  while (1);
}

void Pass(){
  halt(0);
}

void Fail(){
  halt(-1);
}

Context *simple_trap(Event ev, Context *ctx) {
  switch(ev.event) {
    case EVENT_IRQ_TIMER:
      putch('t'); break;
    case EVENT_IRQ_IODEV:
      putch('d'); break;
    case EVENT_YIELD:
      putch('y'); break;
    case EVENT_SYSCALL:
      putstr("test Pass !!!\n");break;
    default:
      break;
  }
  return ctx;
}

void _trm_init() {
  cte_init(simple_trap);
  int ret = main(mainargs);
  halt(ret);
}
